<template>
  <el-space direction="vertical" alignment="flex-start" style="display: block">
    <el-space>
      <el-button type="default">刷新</el-button>
      <el-button type="primary" @click="upsertRef?.open()">新增</el-button>
      <el-button type="danger">删除</el-button>
    </el-space>

    <el-space direction="vertical" fill style="display: block">
      <el-table
        :data="state.list"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" />
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" prop="label" />
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="创建时间" prop="createTime" sortable="custom" />
        <el-table-column label="更新时间" prop="updateTime" sortable="custom" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="upsertRef?.open(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->

      <el-pagination
        background
        layout="prev, pager, next, jumper, total, sizes"
        v-model:current-page="query.page"
        v-model:page-size="query.size"
        :page-sizes="[2, 3, 4, 5]"
        :total="state.pagination.total"
      />
    </el-space>

    <!-- 新增与编辑的弹窗 -->
    <DialogUpsert ref="upsertRef" @success="refresh" />
  </el-space>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watchEffect } from 'vue'
import { getRole } from '@/api/role'
import DialogUpsert from './dialog-upsert.vue'

// 定义接口相关需要的参数
const query = reactive({
  page: 1,
  size: 10,
  keyWord: '',
  order: 'createTime',
  sort: 'desc' as 'desc' | 'asc' | undefined
})

// 后端返回的数据
const state = reactive({
  // 用于存放接口返回的列表数据
  list: [] as IRole[],
  pagination: {
    page: 1,
    size: 10,
    total: 1
  }
})

async function refresh() {
  const { data } = await getRole(query)
  state.list = data.list
  state.pagination = data.pagination
}

/**
 * 处理排序
 */
function handleSortChange(data: any) {
  // order - 是排序规则
  //    descending    -  desc
  //    ascending     -  asc
  // prop - 排序字段
  //    updateTime
  //    createTime
  const { order, prop } = data

  // 需要将 order 赋值 给 query.sort
  query.sort = order ? order.replace('ending', '') : ''
  // 需要将 prop 赋值 给 query.order
  query.order = prop

  // 重新调用接口
  refresh()
}

const upsertRef = ref<InstanceType<typeof DialogUpsert> | null>(null)

// onMounted(() => {
//   refresh()
// })

watchEffect(refresh)
</script>
